use std::fs::{self, ReadDir};

use crate::{list_directory, program_root};
use async_std::task::block_on;


pub fn delete_err_img() {
    let start_time = chrono::Local::now(); //获取结束时间
    let (pic_dir, _) = list_directory::get_directory();
    block_on(async move {
        delete_err_images(pic_dir);
    });
    let end_time = chrono::Local::now(); //获取结束时间
    let duration_time = end_time.signed_duration_since(start_time).to_std().unwrap(); //耗时
    println!(
        "删除任务开始时间 : {:?},结束时间 :{:?},耗时:{:?}",
        start_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        end_time.format("%Y-%m-%d %H:%M:%S").to_string(),
        duration_time
    );
    // 返回主菜单
    program_root();
}

fn delete_err_images(dirs: ReadDir) {
    for entry in dirs {
        let entry = entry.expect("读取文件夹失败");
        let path = entry.path();
        if path.is_dir() {
            println!("正在遍历处理文件夹: {}", path.display());
            delete_err_images(fs::read_dir(path).unwrap()); //递归遍历文件夹
        } else {
            let f_name = path.to_str().unwrap().to_string();
            if f_name.ends_with("Err.png") {
                //如果图片以错误结尾
                println!("正在删除错误Err图片: {}", f_name);
                async_std::task::spawn(async {
                    async_std::fs::remove_file(path)
                        .await
                        .expect("删除文件失败");
                });
            }
        }
    }
}
